import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Form, Input, Toast, Dialog, Button, Picker } from "antd-mobile";
import { BottomBtn, CommonMask } from "@components";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import { createAction, callNativeApi } from "@common/utils";
import {
  PUSH_PAGE_STACK,
  POP_PAGE_STACK,
  SET_PAGE_TITLE,
  SET_SCAN_DATA,
} from "@store/global-state/action-types";
import { getSelectedWarehouses } from "@store/user-profile/selectors";
import { CLEAR_MOVE_DIRECTLY_DATA_ID } from "@store/move-directly/action-types";
import {
  SAGA_MOVE_DIRECTLY_STASH_OPS_DATA,
  SAGA_MOVE_DIRECTLY_LOAD_OPS_FORM,
  SAGA_MOVE_DIRECTLY_FINISH_OPS,
} from "@store/move-directly/saga-types";

const MoveDirectlyNewOpsObj = {
  scanType: null,
};

const NewOps = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [showMask, setShowMask] = useState(false);
  const [disabledInputQty, setDisabledInputQty] = useState(true);
  const warehouseItems = useSelector((state) => getSelectedWarehouses(state));
  const opsFormData = useSelector((state) => state.moveDirectly.opsFormData);
  const dataId = useSelector((state) => state.moveDirectly.dataId);
  const scandata = useSelector((state) => state.globalState.scandata);

  useEffect(() => {
    dispatch(createAction(SET_PAGE_TITLE, "直接移库"));
    return () => {
      MoveDirectlyNewOpsObj.scanType = null;
      dispatch(createAction(SET_SCAN_DATA, null));
      dispatch(createAction(CLEAR_MOVE_DIRECTLY_DATA_ID));
    };
  }, []);

  useEffect(() => {
    if (!warehouseItems || warehouseItems[0].length === 0) {
      Dialog.alert({ content: "请先设置默认使用场景!" });
    } else {
      let warehouse = warehouseItems[0][0];
      form.setFields([
        { name: "warehouseId", value: warehouse.value },
        { name: "warehouseName", value: warehouse.label },
      ]);
    }
  }, [warehouseItems]);

  useEffect(() => {
    if (dataId) {
      dispatch(createAction(SAGA_MOVE_DIRECTLY_LOAD_OPS_FORM, { id: dataId }));
    }
  }, [dataId]);

  useEffect(() => {
    if (opsFormData) {
      form.setFields([
        { name: "warehouseName", value: opsFormData.warehouseName },
        { name: "warehouseId", value: opsFormData.warehouseId },
      ]);
    }
  }, [opsFormData]);

  const setField = ({ parseResult, barcode }) => {
    if (MoveDirectlyNewOpsObj.scanType.endsWith("Location")) {
      form.setFields([
        {
          name: MoveDirectlyNewOpsObj.scanType,
          value: parseResult.locationName,
        },
        {
          name: `${MoveDirectlyNewOpsObj.scanType}Id`,
          value: parseResult.locationId,
        },
      ]);
    } else {
      let { itemName, itemCode, isUnique } = parseResult;
      form.setFields([
        { name: "itemBarcode", value: barcode },
        { name: "itemCode", value: itemCode },
        { name: "itemName", value: itemName },
        { name: "qty", value: parseResult.qty },
      ]);
      setDisabledInputQty(isUnique);
    }
  };

  useEffect(() => {
    if (scandata && showMask) {
      if (!MoveDirectlyNewOpsObj.scanType) {
        return;
      }
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: {
          warehouseId: form.getFieldValue("warehouseId"),
          scanType: MoveDirectlyNewOpsObj.scanType,
          barcode: scandata,
          bizType: "MOVE_DIRECTLY",
        },
        needNonce: false,
      })
        .then((resp) => {
          setShowMask(false);
          let response = resp.data ? resp.data : resp;
          if (response.result.status !== "SUCCESS") {
            Dialog.alert({ content: response.result.errorMessage });
          } else {
            setField({
              parseResult: response.payload,
              barcode: scandata,
            });
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          MoveDirectlyNewOpsObj.scanType = null;
          return;
        })
        .catch((error) => {
          setShowMask(false);
          MoveDirectlyNewOpsObj.scanType = null;
          console.log(error);
        });
    }
  }, [scandata]);

  const markScanType = (type) => {
    setShowMask(true);
    MoveDirectlyNewOpsObj.scanType = type;
  };

  const setWarehouse = ({ items }) => {
    form.setFields([
      { name: "warehouseId", value: items[0].value },
      { name: "warehouseName", value: items[0].label },
    ]);
  };

  const handleContinue = () => {
    form
      .validateFields()
      .then(() => {
        let { warehouseId, itemBarcode, fromLocationId, qty, toLocationId } =
          form.getFieldValue();
        dispatch(
          createAction(SAGA_MOVE_DIRECTLY_STASH_OPS_DATA, {
            dataId,
            warehouseId,
            itemBarcode,
            fromLocationId,
            toLocationId,
            qty,
            callback: () => {
              Toast.show({
                icon: "success",
                content: "保存成功",
                maskClickable: false,
              });
              form.setFields([
                { name: "fromlocationId", value: "" },
                { name: "fromlocationName", value: "" },
                { name: "itemBarcode", value: "" },
                { name: "itemCode", value: "" },
                { name: "itemName", value: "" },
                { name: "qty", value: "" },
                { name: "toLocationId", value: "" },
                { name: "toLocationName", value: "" },
              ]);
              setDisabledInputQty(true);
            },
          })
        );
        return;
      })
      .catch((error) => console.log(error));
  };

  const openDetails = () => {
    let path = `/app/move-directly/details?dataId=${dataId}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const handleFinish = () => {
    dispatch(
      createAction(SAGA_MOVE_DIRECTLY_FINISH_OPS, {
        dataId,
        callback: () => dispatch(createAction(POP_PAGE_STACK, navigate)),
      })
    );
  };

  const checkQty = async (_, value) => {
    if (isNaN(value) || (typeof value === "string" && value.length === 0)) {
      return Promise.reject("请输入数字");
    } else if (parseFloat(value) <= 0) {
      return Promise.reject(`数量须大于0`);
    }
    return Promise.resolve();
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item
            name="warehouseName"
            label="仓库"
            extra={
              dataId ? null : (
                <Button
                  size="small"
                  color="primary"
                  fill="outline"
                  onClick={() => setVisible(true)}
                >
                  选择
                </Button>
              )
            }
          >
            <Input readOnly />
          </Form.Item>

          <Form.Header>
            <span>移库信息</span>
            <span style={{ float: "right" }}>
              累计提交数据: {opsFormData?.recordNum ? opsFormData.recordNum : 0}
              条
            </span>
          </Form.Header>
          <Form.Item
            name="fromLocation"
            label="移出库位"
            rules={REQUIRED_RULE}
            extra={<a onClick={() => markScanType("fromLocation")}>扫码</a>}
          >
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          <Form.Item
            name="itemBarcode"
            label="物料条码"
            rules={REQUIRED_RULE}
            extra={<a onClick={() => markScanType("itemBarcode")}>扫码</a>}
          >
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          <Form.Item name="itemCode" label="物料编码">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="itemName" label="物料名称">
            <Input readOnly />
          </Form.Item>
          <Form.Item
            name="qty"
            label="数量"
            rules={[
              {
                validator: (rule, value, callback) =>
                  checkQty(rule, value, callback),
              },
            ]}
          >
            <Input placeholder="请扫码或输入" readOnly={disabledInputQty} />
          </Form.Item>
          <Form.Item
            name="toLocation"
            label="移入库位"
            rules={REQUIRED_RULE}
            extra={<a onClick={() => markScanType("toLocation")}>扫码</a>}
          >
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
        </Form>
        <Picker
          columns={warehouseItems}
          visible={visible}
          onClose={() => {
            setVisible(false);
          }}
          onConfirm={(_, ext) => setWarehouse(ext)}
        />
      </div>
      <CommonMask showMask={showMask} txt="请扫码" />
      <BottomBtn
        items={[
          { btnTxt: "继续", color: "danger", handler: handleContinue },
          {
            btnTxt: "明细",
            disabled: !(opsFormData?.recordNum > 0),
            handler: openDetails,
          },
          {
            btnTxt: "完成",
            color: "primary",
            disabled: !(opsFormData?.recordNum > 0),
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default NewOps;
